package org.cresource.org.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.cresource.basic.util.AjaxResult;
import org.cresource.basic.util.PageList;
import org.cresource.org.domain.Department;
import org.cresource.org.query.DepartmentQuery;
import org.cresource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门  c层
 */
@RequestMapping("/department")
@RestController//返回数据格式为json是@Controller+@ResponseBody
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {



    @Autowired
    private IDepartmentService departmentService;




    /**
     * 部门添加或修改
     */
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Department department){
            try {
                if(department.getId() == null){
                    departmentService.add(department);
                }else {
                    departmentService.update(department);
                }
                return AjaxResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.me().setMessage("系统繁忙，稍后重试!!!"+e.getMessage());
            }
    }


    /**
     * 通过id查询该条数据
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询一条部门数据",notes = "通过id查询")
    public Department getById(@PathVariable("id") Long id){
        return departmentService.getById(id);
    }


    /**
     * 删除一条数据
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一条部门数据",notes = "通过id删除")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，稍后重试!!!"+e.getMessage());
        }
    }


    /**
     * 分页查询
     */
    @PostMapping
    @ApiOperation(value = "分页查询",notes = "通过PageList进行分页")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }


    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
            departmentService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败"+e.getMessage());
        }
    }


    /**
     * 部门树
     */
    @GetMapping("/tree")
    public List<Department> deptTree(){
        return departmentService.queryDeptTree();
    }
}
